package com.example.springboot.WebService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.springboot.dao.*;
import com.example.springboot.entity.*;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;

import static com.example.springboot.config.MD5.md5;

@RestController
@Api(tags = "WebService ",description = "以下是WebService类提供的接口")
public class WebService {
    @Autowired
    private LoginDao loginDao;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ArticlecontentDao articlecontentDao;
    @Autowired
    private BackgroundDao backgroundDao;
    @Autowired
    private Producer kaptchaProducer;
    private String text;
    @Autowired
    private BackgroundadminDao backgroundadminDao;
    @Autowired
    private BackgroundteacherDao backgroundteacherDao;
    @Autowired
    private CoursedataDao coursedataDao;

    private final String APP_ID = "2021000122690908";
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCL8G+phdF8sfA5q8hR8OW/fkyDZkLTmnSF2hbxkZkbzgds++zRAOot33NbkYKIzkN23mknssKF7pYy9c7yxjkx7lMmaJ0u6CNfHbpXnAm5SriQvAQihyX05mGG6RL55LtWqZWXLzsYjv8h8TyDxgB+jXr1M6hbFWvq1plBworPrcLU+4m/3Trz1UDOxk/0cQQWtqtzKYZ0ugLsdu+ncIOg3kFWQOr2fIKv2UZvwvWlKDSd3DxC1l7HjULzOq/C6wYluez2bByxAF9sGsUgyo/rsB5+rp/6shkevleKmPgqxpSqst532fcIG/O9dejPFhu6s18M5ZRNzw6y53J/IBu7AgMBAAECggEAEg7Xye9rxgSMNFT3h6NncluQ8g/bJcUzriYjec7JDC59BNJJj/rnPT4te65+QrsjN46h0S6fLXtJRJA1wVxU+x1++2Daj7gDAH4skqufEZsT0BGDExWPj1e/VBJ1kWuzxQ4jMJw2qweg4rdnkLWXUL1fFY8x9XcBMw+4PSUmln/riB+XoMGErHUc2Y40MrRSDUbarnlGOd/Q88yW30asbECTCfTg2yg54NaLHcFuSF+W6FWy3prAqZm4aBs68oX53IglF+SVzGhAPBr/07Z+WJapKrmHlCg5m31ACdsbuKlmRXLCQO5Sb6bvesoo1i+gwxhuNJgpR8qOvteeBiQOgQKBgQDVFeGpLGI7ase67ddRMh7iYrXOrOCzROCC73M98vgHh1SN4TsyXwf7N422DGTa3Lk1KQSFrh196+2NiF+VeMuwMUX/nXwcyZH9YvgEXBwBjWqGhbjZVC4glWNlzYgztQWko2dP2DeQDzXSt4iQ6Rk6jV9WFvtDr5Je7E9zdvYK+wKBgQCoH1QBMoyKz9zWlzE8LmbvYAE6FuWbPfRa+pONBVZwcp/4s1o2ZVrEhi077HKJRvglctOPV0Dv+4xGTHHZfLzK76O8bb5GKamDO2DPZdVzybugd4gJA3PnePPqtmbHjfd1EryRJTtwsKGfSniZqpUc6OFUdIbhElxVZ8ZQhzVWQQKBgFLWrOHd1VqQCpHLQPfZ6lPMWC2+26QV1MpSWJTuzinvHJoDw8WzWCD72eW6L8M+J+pYxd9Kb0Cy5akuKSqsyVL39OSIzuVKH61IOm9Hd8PKvG0Ls28Z4MzeBsRfAOJJL6ZvuAw8XG1u3FfM7hSX6izvJO8NBCWuLdMlP0X+K2zdAoGASzEPwiVYhDDpRTSDubXLJd5bTh61fFQeOJ5/ZX/wpAQwFewpOdDk4qZcDsP2if0quJz9j8tnaK2plDtWY/4M9fpt0bWHdxvlC6N/7eJOsCWWe/NZ7SYVLX6EIQKJP1D4Tu0dVxE+32ywLG0DOT74x+BD/yDKvlkW4L+0C4odScECgYBexFIel1yvbOqBubZ7WEGwqf3EViLnMnQ19fnJmpZoentSqChHHd3yinOalqbemmkWYKmWdPIdlcy5hucOdEeSDgXuyAWih0EHcEZiKtx8Z7E4CqQjx1n2wbFEa3rrwgbqZOiPwHE9Fzfbx1S24UA+oDIqG7+c7QMktU0pVpme5A==";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArxHjyflSdM/3uFRzoMVM4Vy2zWQho7WtnEpJSZVEEWOferDJm+msqIrQK+gwWLOFV2VdxtyFsZqrkDxP1zS3z4i76pt5QYEugOkZIIm1IfaLVsM3Bug/9v68LMqTPbClV68nyX40vQJXj+YhZdj8HurIb661s60cJhliylAxVEVW7E+J7I4qyGKrUN++C6A06f8Dh1M4CD159ky1LZuIk6VXpdhiXCBzoTsXgJh2vg0jlOitmSpl4UxDRxht7lhr51D5A130A5wybNNMkV8JRjDEuYz95cciTGpytLO1nOwdLmfeEmd/jTE25IZMbkwKFVvM1YAo7+WR+O3JjffXUQIDAQAB";
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    private final String SIGN_TYPE = "RSA2";
    private final String RETURN_URL = "http://127.0.0.1/returnUrl";

    private String alipayUser="";

    @RequestMapping(value="/HomePage",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="HomePage",notes = "测试Springboot是否稳定的测试接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在")})
    public RedirectView HomePage(){
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://127.0.0.1/index.html");
        return redirectView;
    }
    @RequestMapping(value="/Login",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="Login",notes = "用于学生登录的接口,1 表示登录成功，0 表示登录失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在")})
    @ApiImplicitParams({@ApiImplicitParam(name="Username",value = "用户账号",dataType="String"),@ApiImplicitParam(name="Password",value = "用户密码",dataType="String")})
    public UserInfo Login(String Username,String Password){
        LambdaQueryWrapper<UserInfo> loginLambdaQueryWrapper=new LambdaQueryWrapper<>();
        loginLambdaQueryWrapper.eq(UserInfo::getUsername,Username).eq(UserInfo::getPassword,Password);
        List<UserInfo> LoginList=userInfoDao.selectList(loginLambdaQueryWrapper);
        if(LoginList.size()!=0){
            return userInfoDao.selectById(LoginList.get(0).getId());
        }else{
            return null;
        }
    }
    @RequestMapping(value="/Course",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="Course",notes = "用于获取课程信息的接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在")})
    public List<Course> SelectCourse(){
        List<Course> courseList=courseDao.selectList(null);
        return courseList;
    }
    @RequestMapping(value="/Teacher",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="Teacher",notes = "用户获取教师信息的接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在")})
    public List<Teacher> SelectTeahcer(){
        List<Teacher> TeacherList=teacherDao.selectList(null);
        return TeacherList;
    }
    @RequestMapping(value="/Article",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="Article",notes = "用户获取文章信息的接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在")})
    public List<Article> SelectArticle(){
        List<Article> articleList=articleDao.selectList(null);
        return articleList;
    }
    @RequestMapping(value="/UserInfo",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UserInfo",notes = "用户获取用户信息的接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在")})
    public List<UserInfo> UserInfo(){
        return userInfoDao.selectList(null);
    }
    @RequestMapping(value="/ArticleContent",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="ArticleContent",notes = "用于获取文章内容的接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在")})
    @ApiImplicitParams({@ApiImplicitParam(name="id",value = "文章id",dataType="Intege")})
    public Articlecontent ArticleContent(int id){
        return articlecontentDao.selectById(id);
    }
    @RequestMapping(value="/AdminLogin",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="AdminLogin",notes = "用于管理员登录的api接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="user",value = "用户账号",dataType="String"),@ApiImplicitParam(name="userPassword",value = "用户密码",dataType="String"),@ApiImplicitParam(name="userCode",value = "验证码",dataType="String"),@ApiImplicitParam(name="SelectValue",value = "身份标识",dataType="Integer")})
    public int AdminLogin(String user,String userPassword,String userCode,int SelectValue){
        System.out.println(user+"\t"+userPassword+"\t"+userCode+"\t"+SelectValue);
        if(SelectValue==1){
            LambdaQueryWrapper<Backgroundadmin> backgroundadminLambdaQueryWrapper=new LambdaQueryWrapper<>();
            backgroundadminLambdaQueryWrapper.eq(Backgroundadmin::getAdmin,user).eq(Backgroundadmin::getAminpassword,userPassword);
            if(backgroundadminDao.selectList(backgroundadminLambdaQueryWrapper).size()!=0 && this.text.equals(userCode.toUpperCase())){
                return 1;
            }else{
                return 0;
            }
        }else if(SelectValue==2){
            LambdaQueryWrapper<Backgroundteacher> backgroundteacherLambdaQueryWrapper=new LambdaQueryWrapper<>();
            backgroundteacherLambdaQueryWrapper.eq(Backgroundteacher::getTeacher,user).eq(Backgroundteacher::getTacherpassword,userPassword);
            if(backgroundteacherDao.selectList(backgroundteacherLambdaQueryWrapper).size()!=0 && this.text.equals(userCode.toUpperCase())){
                return 2;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    @RequestMapping(value = "/Kaptcha",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="Kaptcha",notes = "用于获取验证码的api接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        //    生成验证码
        String text= kaptchaProducer.createText();
        //    生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(text);
        //    将图片传入session
        session.setAttribute(" kaptcha", text);
        this.text=text;
        //    将图片输出到前端(图片+格式)
        response.setContentType("image/png");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("响应验证码失败");
        }
    }
    @RequestMapping(value = "/Upload",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="Upload",notes = "用于获取验证码的api接口")
    public ResponseEntity<byte[]> doReport() {
        try {
            File file = new File("../UpLoad/");

            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment",
                    new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1"));
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 获取文件的字节数组 - 需要使用commons-io依赖包
            byte[] content = FileUtils.readFileToByteArray(file);
            return new ResponseEntity<>(content, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping(value = "/LikeCourse",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="LikeCourse",notes = "用于课程搜索的api接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="CourseName",value = "课程名",dataType="String"),@ApiImplicitParam(name="CourseUp",value = "上传用户",dataType="String"),@ApiImplicitParam(name="CourseInformation",value = "课程简介",dataType="String"),@ApiImplicitParam(name="CourseDate",value = "课程上传时间",dataType="String")})
    public List<Course> LikeCourse(String CourseName,String CourseUp,String CourseInformation,String CourseDate){
        if(CourseName==null&&CourseUp==null&&CourseInformation==null&&CourseDate==null){
            return courseDao.selectList(null);
        }else{
            LambdaQueryWrapper<Course> loginLambdaQueryWrapper=new LambdaQueryWrapper<>();
            loginLambdaQueryWrapper
                    .likeRight(Course::getCourseName,CourseName)
                    .or()
                    .likeRight(Course::getCourseUp,CourseUp)
                    .or()
                    .likeRight(Course::getCourseInformation,CourseInformation)
                    .or()
                    .likeRight(Course::getCourseDate,CourseDate);
            return courseDao.selectList(loginLambdaQueryWrapper);
        }
    }
    @RequestMapping(value = "/CourseDetails",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="CourseDetails",notes = "用于获取课程详情的api接口")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="CourseId",value = "课程ID",dataType="Integer")})
    public List<Coursedata> CourseDetails(int CourseId){
        LambdaQueryWrapper<Coursedata> coursedataLambdaQueryWrapper=new LambdaQueryWrapper<>();
        coursedataLambdaQueryWrapper.eq(Coursedata::getCourseid,CourseId);
        return coursedataDao.selectList(coursedataLambdaQueryWrapper);
    }
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="register",notes = "用于用户注册的api接口 1，注册成功 0，注册失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="username",value = "用户名",dataType="Stringr"),@ApiImplicitParam(name="userpassword",value = "密码",dataType="Integer")})
    public int Register(String username,String userpassword){
        UserInfo userInfo=new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(userpassword);
        userInfo.setSculpture(null);
        userInfo.setEMailbox(null);
        userInfo.setPhone("10086");
        userInfo.setMember(0);
        userInfo.setMoney(100);
        int insertstatus = userInfoDao.insert(userInfo);
        if(insertstatus==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/UpdataUser",method = RequestMethod.POST)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdataUser",notes = "用于更新用户信息的api接口 1，更新成功 0，更新失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="username",value = "用户账号",dataType="String"),@ApiImplicitParam(name="password",value = "用户密码",dataType="String"),@ApiImplicitParam(name="eMailbox",value = "用户邮箱",dataType="String"),@ApiImplicitParam(name="phone",value = "身份电话",dataType="String"),@ApiImplicitParam(name="id",value = "用户id",dataType="Integer",required = true)})
    public int UpdataUser(int id,String username,String password,String eMailbox,String phone){
        UserInfo userInfo=new UserInfo();
        userInfo.setId(id);
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        userInfo.setEMailbox(eMailbox);
        userInfo.setPhone(phone);
        int updataeStatus = userInfoDao.updateById(userInfo);
        if(updataeStatus==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/UpdataCourse",method = RequestMethod.POST)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdataCourse",notes = "用于更新用户信息的api接口 1，更新成功 0，更新失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="Course_Id",value = "课程ID",dataType="String"),@ApiImplicitParam(name="Course_name",value = "课程名",dataType="String"),@ApiImplicitParam(name="Course_up",value = "课程上传人",dataType="String"),@ApiImplicitParam(name="Course_Date",value = "课程上传时间",dataType="String"),@ApiImplicitParam(name="Course_information",value = "课程简介",dataType="Integer",required = true)})
    public int UpdataCourse(int Course_Id,String Course_name,String Course_up,String Course_Date,String Course_information){
        Course course=new Course();
        course.setId(Course_Id);
        course.setCourseName(Course_name);
        course.setCourseUp(Course_up);
        course.setCourseDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date().getTime()));
        course.setCourseInformation(Course_information);
        course.setClassification(null);
        if(courseDao.updateById(course)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/UpdateUserAdmin",method = RequestMethod.POST)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdateUserAdmin",notes = "用于更新用户信息的api接口 1，更新成功 0，更新失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="username",value = "用户账号",dataType="String"),@ApiImplicitParam(name="userPassword",value = "用户密码",dataType="String"),@ApiImplicitParam(name="eMailbox",value = "用户邮箱",dataType="String"),@ApiImplicitParam(name="phone",value = "身份电话",dataType="String"),@ApiImplicitParam(name="id",value = "用户id",dataType="Integer",required = true),@ApiImplicitParam(name="eMailbox",value = "用户邮箱",dataType="String"),@ApiImplicitParam(name="phone",value = "身份电话",dataType="String")})
    public int UpdateUserAdmin(int id,String username,String password,String eMailbox,String phone){
        UserInfo userInfo=new UserInfo();
        userInfo.setId(id);
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        userInfo.setEMailbox(eMailbox);
        userInfo.setPhone(phone);
        int updataeStatus = userInfoDao.updateById(userInfo);
        if(updataeStatus==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/UpdateArticle",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdateArticle",notes = "用于更新文章的api接口 1，更新成功 0，更新失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="articlename",value = "文章发布人",dataType="String"),@ApiImplicitParam(name="articleregion",value = "文章标题",dataType="String"),@ApiImplicitParam(name="articledesc",value = "文章简介",dataType="String"),@ApiImplicitParam(name="articletype",value = "文章封面",dataType="String"),@ApiImplicitParam(name="articleid",value = "文章id",dataType="Integer",required = true)})
    public int UpdateArticle(String articlename,String articleregion,String articledesc,int articleid,String articletype){
        Article article=new Article();
        article.setId(articleid);
        article.setArticleCover(articletype);
        article.setArticleTitle(articleregion);
        article.setArticleInformation(articledesc);
        article.setArticleAuthor(articlename);
        if(articleDao.updateById(article)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/DeleteArticle",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="DeleteArticle",notes = "用于更新文章的api接口 1，更新成功 0，更新失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="articleid",value = "文章id",dataType="Integer",required = true)})
    public int DeleteArticle(int articleid){
        System.out.println(articleid);
        if(articleDao.deleteById(articleid)==1){
            return 1;
        }else {
            return 0;
        }
    }
    @RequestMapping(value="/UpdateCourse",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdateCourse",notes = "用于更新课程的api接口 1，更新成功 0，更新失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="courseCover",value = "课程封面",dataType="String"),@ApiImplicitParam(name="courseName",value = "课程标题",dataType="String"),@ApiImplicitParam(name="courseUp",value = "课程发布人",dataType="String"),@ApiImplicitParam(name="courseInformation",value = "课程简介",dataType="String"),@ApiImplicitParam(name="CourseId",value = "课程id",dataType="Integer",required = true),@ApiImplicitParam(name="member",value = "课程权限",dataType="Integer"),@ApiImplicitParam(name="classification",value = "课程分类",dataType="Integer"),@ApiImplicitParam(name="courseUp",value = "课程发布人",dataType="String"),@ApiImplicitParam(name="courseDate",value = "上传时间",dataType="String")})
    public int UpdateCourse(int CourseId,String courseCover,String courseName,String courseUp,String courseInformation,int member,int classification,String courseDate){
        Course course=new Course();
        course.setId(CourseId);
        course.setCourseCover(courseCover);
        course.setCourseName(courseName);
        course.setCourseUp(courseUp);
        course.setCourseInformation(courseInformation);
        course.setMember(member);
        course.setClassification(classification);
        course.setCourseDate(courseDate);
        System.out.println(CourseId);
//        System.out.println(CourseId+courseCover+courseName+courseUp+courseInformation+member+classification+courseDate);
        if(courseDao.updateById(course)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/purchase",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="purchase",notes = "用于购买会员的api接口 1，更新成功 0，更新失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="Id",value = "用户id",dataType="String")})
    public int purchase(int Id){
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getId,Id);
        List<UserInfo> userInfoList=userInfoDao.selectList(userInfoLambdaQueryWrapper);
        int money=userInfoList.get(0).getMoney();
        if((money-35)>=0){
            UserInfo userInfo=new UserInfo();
            userInfo.setId(Id);
            userInfo.setMoney(money-35);
            userInfo.setMember(1);
            userInfoDao.updateById(userInfo);
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/DeleteCourse",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="DeleteCourse",notes = "用于购买会员的api接口 1，删除成功 0，删除失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="CourseId",value = "课程id",dataType="Integer",required = true)})
    public int DeleteCourse(int CourseId){
        if(courseDao.deleteById(CourseId)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/UpdateTeahcer",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdateTeahcer",notes = "用于更新教师信息的api接口 1，删除成功 0，删除失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    public int UpdateTeahcer(int id,String teacherImage,String teacherName,String teacherInformation,String teacherIntroduce, String teacherCharacteristic,String teacherStyle){
        Teacher teacher=new Teacher();
        teacher.setId(id);
        teacher.setTeacherImage(teacherImage);
        teacher.setTeacherName(teacherName);
        teacher.setTeacherStyle(teacherStyle);
        teacher.setTeacherInformation(teacherInformation);
        teacher.setTeacherIntroduce(teacherIntroduce);
        teacher.setTeacherCharacteristic(teacherCharacteristic);
        if(teacherDao.updateById(teacher)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/DeleteTeacher",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="DeleteTeacher",notes = "用于删除教师信息的api接口 1，删除成功 0，删除失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="TeacherId",value = "教师id",dataType="Integer",required = true)})
    public int DeleteTeacher(int TeacherId){
        if(teacherDao.deleteById(TeacherId)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/UpdateUser",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdateUser",notes = "用于更新用户信息的api接口 1，删除成功 0，删除失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="id",value = "用户id",dataType="Integer",required = true),@ApiImplicitParam(name="username",value = "用户账号",dataType="String"),@ApiImplicitParam(name="password",value = "用户密码",dataType="String"),@ApiImplicitParam(name= "static/admin_sculpture",value = "用户头像",dataType="String"),@ApiImplicitParam(name="eMailbox",value = "用户邮箱",dataType="String"),@ApiImplicitParam(name="phone",value = "用户电话",dataType="String"),@ApiImplicitParam(name="member",value = "用户权限",dataType="Integer"),@ApiImplicitParam(name="money",value = "用户余额",dataType="Integer")})
    public int UpdateUser(int id,String username,String password,String sculpture,String eMailbox,String phone,int member,int money) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        userInfo.setSculpture(sculpture);
        userInfo.setEMailbox(eMailbox);
        userInfo.setPhone(phone);
        userInfo.setMember(member);
        userInfo.setMoney(money);
        if (userInfoDao.updateById(userInfo) == 1) {
            return 1;
        } else {
            return 0;
        }
    }
    @RequestMapping(value="/DeleteUserinfo",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="DeleteUserinfo",notes = "用于删除教师信息的api接口 1，删除成功 0，删除失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="UserinfoId",value = "教师id",dataType="Integer",required = true)})
    public int DeleteUserinfo(int UserinfoId){
        if(userInfoDao.deleteById(UserinfoId)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/UpdateBackgroundteacher",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdateBackgroundteacher",notes = "用于删除教师信息的api接口 1，删除成功 0，删除失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    @ApiImplicitParams({@ApiImplicitParam(name="UserinfoId",value = "教师id",dataType="Integer",required = true)})
    public int UpdateBackgroundteacher(String user,String password,String email,String phone,String iamge){
        LambdaQueryWrapper<Backgroundteacher> backgroundteacherLambdaQueryWrapper=new LambdaQueryWrapper<>();
        backgroundteacherLambdaQueryWrapper.eq(Backgroundteacher::getTeacher,md5(user));
        Backgroundteacher backgroundteacher=new Backgroundteacher();
        backgroundteacher.setTeacher(md5(user));
        backgroundteacher.setTacherpassword(md5(password));
        backgroundteacher.setId(backgroundteacherDao.selectList(backgroundteacherLambdaQueryWrapper).get(0).getId());
        if(backgroundteacherDao.updateById(backgroundteacher)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/uploadCourse",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="uploadCourse",notes = "用于更新课程信息的api接口 1，删除成功 0，删除失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    public int uploadCourse(String courseName,String courseUp,String courseInformation,String courseImage){
        Course course=new Course();
        course.setCourseName(courseName);
        course.setCourseUp(courseUp);
        course.setCourseInformation(courseInformation);
        course.setCourseCover(courseImage);
        course.setCourseDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date().getTime()));
        course.setMember(0);
        course.setClassification(1);
        course.setTeachername("teacher1");
        if(courseDao.insert(course)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping(value="/UpdateAdmin",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="UpdateAdmin",notes = "用于更管理账号的api接口 1，删除成功 0，删除失败")
    @ApiResponses({@ApiResponse(code=401,message = "请求参数出错"),@ApiResponse(code=404,message = "页面不存在"),@ApiResponse(code=403,message = "服务器内部发生错误")})
    public int UpdateAdmin(String password,String username){
        LambdaQueryWrapper<Backgroundadmin> backgroundadminLambdaQueryWrapper=new LambdaQueryWrapper<>();
        backgroundadminLambdaQueryWrapper.eq(Backgroundadmin::getAdmin,md5(username));
        Backgroundadmin backgroundadmin=new Backgroundadmin();
        backgroundadmin.setId(backgroundadminDao.selectList(backgroundadminLambdaQueryWrapper).get(0).getId());
        backgroundadmin.setAdmin(md5(username));
        backgroundadmin.setAminpassword(md5(password));
        if(backgroundadminDao.updateById(backgroundadmin)==1){
            return 1;
        }else{
            return 0;
        }
    }
    @RequestMapping("/alipay")
    @CrossOrigin(origins = "*")
    @ApiOperation(value="alipay",notes = "用于支付宝支付的页面")
    public void alipay(String orderId,String username, HttpServletResponse httpResponse) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        String out_trade_no = orderId.toString();
        //付款金额，必填
        String total_amount = "35.00";
        //订单名称，必填
        String subject = "订单测试";
        alipayUser=username;
        //商品描述，可空
        String body = "";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + total_amount + "\","
                + "\"body\":\"" + body + "\","
//                + "\"user\":\"" + user + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value="returnUrl",notes = "支付成功后调用的接口")
    public RedirectView returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);
            LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
            userInfoLambdaQueryWrapper.eq(UserInfo::getUsername,alipayUser);
            int userId=userInfoDao.selectList(userInfoLambdaQueryWrapper).get(0).getId();
            int userMoney=userInfoDao.selectList(userInfoLambdaQueryWrapper).get(0).getMoney();
            UserInfo userInfo=new UserInfo();
            userInfo.setId(userId);
            userInfo.setMoney(Integer.valueOf(userMoney+total_amount));
            userInfoDao.updateById(userInfo);
            RedirectView redirectView = new RedirectView();
            redirectView.setUrl("http://127.0.0.1:8080/secondsheets/ThatPerson/PersonalInformation");
            return redirectView;
        }else{
            RedirectView redirectView = new RedirectView();
            redirectView.setUrl("http://127.0.0.1:8080/secondsheets/ThatPerson/PersonalInformation");
            return redirectView;
        }
    }
    @RequestMapping(value="/getAdminImage",method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    public String getAdminImage(String userName){
        LambdaQueryWrapper<Backgroundadmin> backgroundadminLambdaQueryWrapper=new LambdaQueryWrapper<>();
        backgroundadminLambdaQueryWrapper.eq(Backgroundadmin::getAdmin,md5(userName));
        int adminId=backgroundadminDao.selectList(backgroundadminLambdaQueryWrapper).get(0).getId();
        return backgroundadminDao.selectById(adminId).getImage();
    }
    @RequestMapping(value="/getteacherImage", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    public String getteacherImage(String userName){
        LambdaQueryWrapper<Backgroundteacher> backgroundadminLambdaQueryWrapper=new LambdaQueryWrapper<>();
        backgroundadminLambdaQueryWrapper.eq(Backgroundteacher::getTeacher,userName);
        int adminId=backgroundteacherDao.selectList(backgroundadminLambdaQueryWrapper).get(0).getId();
        return backgroundteacherDao.selectById(adminId).getImage();
    }
    @RequestMapping(value = "/GetUserInfo", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value = "GetUserInfo", notes = "获取用户信息")
    @ApiResponses({ @ApiResponse(code = 200, message = "上传成功"), @ApiResponse(code = 400, message = "参数错误")})
    public UserInfo GetUserInfo(int UserId){
        return userInfoDao.selectById(UserId);
    }
    @RequestMapping(value = "/DeleteUserInfo", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value = "DeleteUserInfo", notes = "用户删除用户")
    public int DeleteUserInfo(int id){
        return userInfoDao.deleteById(id);
    }
    @RequestMapping(value = "/Usergrowthtrend", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value = "Usergrowthtrend", notes = "获取每天用户的增长率")
    public int[] Usergrowthtrend(){
        Random random=new Random();
        int[] list=new int[7];
        for(int i=0;i<7;i++){
            list[i]=random.nextInt(100);
        }
        return list;
    }
    @RequestMapping(value = "/Userproportion", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value = "Userproportion", notes = "获取各用户占比")
    public Map<String,Float> Userproportion(){
        Map<String,Float> map=new HashMap<>();
        float admin=backgroundadminDao.selectList(null).size();
        float teacher=backgroundteacherDao.selectList(null).size();
        float user=userInfoDao.selectList(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getMember,0)).size();
        float VipUser=userInfoDao.selectList(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getMember,1)).size();
        float total=admin+teacher+user+VipUser;
        map.put("管理员",admin/total);
        map.put("教师",teacher/total);
        map.put("普通用户",user/total);
        map.put("会员用户",VipUser/total);
        return map;
    }
    @RequestMapping(value = "/Moduleheat", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value = "Moduleheat", notes = "获取各模块点击率")
    public Map<String,Float> Moduleheat(){
        Map<String,Float> map=new HashMap<>();
        Formatter formatter=new Formatter();
        Random random=new Random();
        float course=random.nextInt(1000);
        float article=random.nextInt(1000);
        float HomePage=random.nextInt(1000);
        float teacher=random.nextInt(1000);
        float total=course+article+teacher+HomePage;
        map.put("课程", course/total);
        map.put("文章", article/total);
        map.put("首页", HomePage/total);
        map.put("名师", teacher/total);
        return map;
    }
    @RequestMapping(value = "/Videopopularity", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value = "Videopopularity", notes = "获取各视频点击量占比")
    public Map<String,Float> Videopopularity(){
        Map<String,Float> map=new HashMap<>();
        Random random=new Random();
        float MysqlCount=random.nextInt(1000);
        float JavaCount=random.nextInt(1000);
        float PythonCount=random.nextInt(1000);
        float CCount=random.nextInt(1000);
        float LinuxCount=random.nextInt(1000);
        float OtherCount=random.nextInt(1000);
        float total=MysqlCount+JavaCount+PythonCount+CCount+LinuxCount+OtherCount;
        map.put("Mysql",MysqlCount/total);
        map.put("Java",JavaCount/total);
        map.put("Python",PythonCount/total);
        map.put("C++",CCount/total);
        map.put("Linux",LinuxCount/total);
        map.put("其它",OtherCount/total);
        return map;
    }
    @RequestMapping(value = "/Membershipproportion", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    @ApiOperation(value = "Membershipproportion", notes = "获取用户每日增长量")
    public int[][] Membershipproportion(){
        Random random=new Random();
        int[][] arr=new int[7][2];
        for(int i=0;i<7;i++){
            arr[i][0]=random.nextInt(100);
            arr[i][1]=random.nextInt(100);
        }
        return arr;
    }
}
